from django.contrib.auth.models import User
from rest_framework import serializers, fields
from rest_framework.fields import SerializerMethodField

from blog.models import Blog, Comment


class UserRegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'password', 'email']


class UserLoginSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['username', 'password']


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username']


class BlogListSerializer(serializers.ModelSerializer):

    author = UserSerializer(read_only=True)

    class Meta:
        model = Blog
        fields = ['id', 'title', 'author', 'create_time', "tags", "content"]


class BlogDetailSerializer(serializers.ModelSerializer):
    author = UserSerializer(read_only=True)
    comments = SerializerMethodField()

    class Meta:
        model = Blog
        fields = ['id', 'title', 'author', 'create_time', "tags", "content", 'read_num', 'comments']

    def get_comments(self, obj):

        c_qs = Comment.objects.filter(blog_id = obj.id)
        comments = CommentListSerializer(c_qs, many=True).data
        return comments


class BlogPostSerializer(serializers.ModelSerializer):

    class Meta:
        model = Blog
        fields = ['title', "tags", "content", ]

    def create(self, validated_data):
        user = self.context['request'].user
        blog = Blog.objects.create(
            author=user,
            **validated_data
        )
        return blog


class CommentListSerializer(serializers.ModelSerializer):

    user = UserSerializer(read_only=True)

    class Meta:
        model = Comment
        fields = ['content', 'user', 'blog', 'create_time']


class CommentSerializer(serializers.ModelSerializer):

    class Meta:
        model = Comment
        fields = ['content', 'blog']

    def create(self, validated_data):
        user = self.context['request'].user
        comment = Comment.objects.create(
            user=user,
            **validated_data
        )
        return comment
